package com.towa.ninemanmorris;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;

import android.os.AsyncTask;
import android.util.Log;

public class GroupHighscoreTasker extends
		AsyncTask<String, Void, HighscoreWrapper> {

	@Override
	protected HighscoreWrapper doInBackground(String... params) {
		Socket socket = null;
		PrintWriter pw;
		BufferedReader br;
		HighscoreWrapper hsw = new HighscoreWrapper();
		try {
			socket = new Socket(NineManMorrisConstants.INET_ADDRESS, NineManMorrisConstants.INET_PORT);
			pw = new PrintWriter(socket.getOutputStream());
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			pw.println(params[0]);
			pw.flush();
			String string = br.readLine();
			String[] strings = string.split("::");
			int length = Integer.parseInt(strings[1]);
			ArrayList<MemberWrapper> memList = new ArrayList<MemberWrapper>();
			for (int i = 0; i < length; i++) {
				String temp = br.readLine();
				String[] temps = temp.split("::");
				MemberWrapper mw = new MemberWrapper();
				mw.setUsername(temps[0]);
				mw.setWin(Integer.parseInt(temps[1]));
				mw.setLoss(Integer.parseInt(temps[2]));
				memList.add(mw);
			}
			hsw.setMembers(memList);
			hsw.setGroupName(strings[0]);
		} catch (UnknownHostException e) {
			Log.e("GroupHighscoreTasker", e.toString());
		} catch (IOException e) {
			Log.e("GroupHighscoreTasker", e.toString());
		}
		return hsw;
	}

}
